package mallindex

import (
	"context"
	"strconv"
	"strings"

	// "fmt"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/product/rpc/productclient"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetCorridorByIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetCorridorByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCorridorByIdLogic {
	return &GetCorridorByIdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetCorridorByIdLogic) GetCorridorById(
	req *types.LiveTileIdReq,
	headers *[]*types.Header,
) (*types.GoodsSectionInfo, error) {
	if req.Id == nil || *req.Id == 0 {
		return &types.GoodsSectionInfo{}, nil
	}

	userId := jwt.GetUserId(l.ctx)

	preload := "product:Id,Title,Slug"
	eagerLoad := "product:productTerm,productMeta,productMedia"
	preload += ";productTerm:Id,Name,Slug"
	preload += ";productMeta:mediaId,mediaUrl,retailPriceMin"
	preload += ";productMedia:Uid,Url"

	var filters []string
	filters = append(filters, "virtual,equalTo:"+strconv.FormatInt(int64(globalkey.ProductTypePhysical), 10))
	filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))

	preFilterEntity := "productTerm"
	preFilter := "Id,equalTo:" + strconv.FormatUint(*req.Id, 10)

	res, err := l.svcCtx.ProductRpc.GetProductList(l.ctx, &productclient.BaseListReq{
		Preload:         pointy.GetPointer(preload),
		EagerLoad:       pointy.GetPointer(eagerLoad),
		PreFilterEntity: pointy.GetPointer(preFilterEntity),
		PreFilter:       pointy.GetPointer(preFilter),
		Filter:          pointy.GetPointer(strings.Join(filters, ";")),
		VisitorId:       pointy.GetPointer(userId),
		PlatformId:      pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		return nil, err
	}

	resp := &types.GoodsSectionInfo{}
	if len(res.List) > 0 {
		var hasTag bool
		for _, v := range res.List {
			if !hasTag && len(v.Tags) > 0 {
				for _, tag := range v.Tags {
					if tag.Id != nil && *tag.Id == *req.Id {
						hasTag = true
						resp.TagList = append(resp.TagList, &types.TermInfo{
							Id:   tag.Id,
							Name: tag.Name,
							Slug: tag.Slug,
						})
						break
					}
				}
			}

			var retailPriceMin *string
			var mediaUrl *string
			if len(v.Meta) > 0 {
				for _, m := range v.Meta {
					if m.Key == nil || m.Value == nil {
						continue
					}

					val := *m.Value
					switch *m.Key {
					case "retailPriceMin":
						retailPriceMin = pointy.GetPointer(val)
					case "mediaUrl":
						mediaUrl = pointy.GetPointer(val)
					}
				}
			}

			if len(v.Media) > 0 {
				for _, m := range v.Media {
					if mediaUrl != nil {
						break
					}

					var url string
					if m.Url != nil && len(*m.Url) > 0 {
						url = *m.Url
					}
					if len(url) == 0 && m.Uri != nil && len(*m.Uri) > 0 {
						url = *m.Uri
					}
					mediaUrl = pointy.GetPointer(url)
				}
			}

			resp.GoodsList = append(resp.GoodsList, &types.GoodsInfo{
				Id:       v.Id,
				Title:    v.Title,
				Slug:     v.Slug,
				MinPrice: retailPriceMin,
				ImageUrl: mediaUrl,
			})
		}
	}

	return resp, nil
}
